import 'package:pt_manage/common/global.dart';
import 'package:pt_manage/dao/site_user_info_dao.dart';
import 'package:pt_manage/db/base/dao_base.dart';
import 'package:pt_manage/db/query/query_config.dart';
import 'package:pt_manage/db/query/query_page.dart';
import 'package:pt_manage/model/Site.dart';
import 'package:pt_manage/model/site_user_info.dart';

class SiteDao extends DaoBase<Site> {
  SiteDao(): super(
    tableName: "site",
    createSql: """
      CREATE TABLE IF NOT EXISTS site (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        timezoneOffset TEXT,
        description TEXT,
        url TEXT NOT NULL,
        icon TEXT,
        tags TEXT,  -- 存储 JSON 格式的标签数组
        host TEXT NOT NULL,
        schema TEXT,
        cdn TEXT,  -- 存储 JSON 格式的 CDN 地址数组
        apiCdn TEXT,  -- 存储 JSON 格式的 API CDN 地址数组
        tokenRequired INTEGER DEFAULT 0,  -- 使用 0 或 1 表示 false 或 true
        formerHosts TEXT,  -- 存储 JSON 格式的旧域名数组
        uploadRateLimit int,
        passKey TEXT,
        authToken TEXT,
        cookie TEXT,
        createTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updateTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    CREATE TRIGGER IF NOT EXISTS trigger_site_updated_at AFTER UPDATE ON site
    BEGIN
        UPDATE site SET updateTime = CURRENT_TIMESTAMP WHERE rowid == NEW.rowid;
    END;
    """
  );

  @override
  Site fromJson(Map<dynamic, dynamic> json) {
    return Site.fromJson(json);
  }

  @override
  int getId(Site obj) {
    return obj.id!;
  }

  @override
  Map<String, dynamic> toJson(Site obj) {
    return obj.toJson();
  }

  Future<QueryPage<Site>> pageByUserInfo(QueryPage<Site> page, List<QueryConfig> configs, {columns, groupBy, orderBy}) async {
    QueryPage<Site> result = await pageQueryList(page, configs, columns: columns, groupBy: groupBy, orderBy: orderBy);
    SiteUserInfoDao siteUserInfoDao = Global.getDb<SiteUserInfoDao>();
    List<SiteUserInfo>? siteUserInfoList = await siteUserInfoDao.listQuery(QueryConfig<List>(field: "site", condition: Condition.IN, value: result.data.map((item) => item.name).toList()));
    if (siteUserInfoList == null) return result;
    Map<int, SiteUserInfo> siteUserInfoMap = { for (var item in siteUserInfoList) item.siteId ?? 0 : item };
    for (Site item in page.data) {
      item.userInfo = siteUserInfoMap[item.id];
    }
    return result;
  }

}